package com.leyou.service.impl;

import com.item.dto.SpecGroupDTO;
import com.item.dto.SpecParamDTO;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.BeanHelper;
import com.leyou.entity.SpecGroup;
import com.leyou.entity.SpecParam;
import com.leyou.mapper.SpecGroupMapper;
import com.leyou.mapper.SpecParamMapper;
import com.leyou.service.SpecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SpecServiceImpl implements SpecService {


    @Autowired
    private SpecGroupMapper specGroupMapper;

    @Autowired
    private SpecParamMapper SpecParamMapper;

    public List<SpecGroupDTO> queryGroupByCategory(Long id) {
        // 查询规格组
        SpecGroup s = new SpecGroup();
        s.setCid(id);
        List<SpecGroup> list = specGroupMapper.select(s);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.BRAND_NOT_FOUND);
        }
        // 对象转换
        return BeanHelper.copyWithCollection(list, SpecGroupDTO.class);
    }

//    查询规格参数
    @Override
    public List<SpecParamDTO> querySpecParams(Long gid,Long cid,Boolean searching) {
        if (gid == null && cid == null) {
            throw new LyException(ExceptionEnum.INVALID_PARAM_ERROR);
        }

        SpecParam s = new SpecParam();
        s.setCid(cid);
        s.setGroupId(gid);
        s.setSearching(searching);

        List<SpecParam> list = SpecParamMapper.select(s);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.SPEC_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, SpecParamDTO.class);
    }

//    查询规格参数组，及组内参数
    @Override
    public List<SpecGroupDTO> querySpecsByCid(Long id) {

        // 查询规格组
        List<SpecGroupDTO> groupList = queryGroupByCategory(id);
        // 查询分类下所有规格参数
        List<SpecParamDTO> params = querySpecParams(null, id, null);
        // 将规格参数按照groupId进行分组，得到每个group下的param的集合
        Map<Long, List<SpecParamDTO>> paramMap = params.stream()
                .collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        // 填写到group中
        for (SpecGroupDTO groupDTO : groupList) {
            groupDTO.setParams(paramMap.get(groupDTO.getId()));
        }
        return groupList;
    }
}
